from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

# 模拟数据库 - 实际项目中应替换为真实数据库操作
customers_db = [
    {'customer_id': '1001', 'customer_name': '张三', 'pid': '110101199001011234', 'telephone': '13800138000', 'address': '北京市朝阳区'},
    {'customer_id': '1002', 'customer_name': '李四', 'pid': '310101199202025678', 'telephone': '13900139000', 'address': '上海市浦东新区'}
]

cards_db = [
    {'card_id': '6222021234567890123', 'customer_id': '1001', 'deposit_type': '活期存款', 'balance': 15000.50, 'open_date': '2023-01-15', 'is_report_loss': False},
    {'card_id': '6222029876543210987', 'customer_id': '1002', 'deposit_type': '定期存款', 'balance': 50000.00, 'open_date': '2023-03-20', 'is_report_loss': False}
]

deposits_db = [
    {'id': 1, 'card_id': '6222021234567890123', 'amount': 10000.00, 'date': '2023-05-01', 'type': '存款'},
    {'id': 2, 'card_id': '6222029876543210987', 'amount': 50000.00, 'date': '2023-03-20', 'type': '存款'}
]

transactions_db = [
    {'id': 1, 'from_card': '6222021234567890123', 'to_card': '6222029876543210987', 'amount': 2000.00, 'date': '2023-06-10', 'status': '成功'},
    {'id': 2, 'from_card': '6222021234567890123', 'to_card': '6222021111111111111', 'amount': 500.00, 'date': '2023-06-15', 'status': '失败'}
]

# 客户管理路由 - 已实现
@admin_bp.route('/customers', methods=['GET'])
@jwt_required()
def get_customers():
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 10, type=int)
    search = request.args.get('search', '')

    # 模拟分页和搜索
    start = (page - 1) * per_page
    end = start + per_page
    filtered = [c for c in customers_db if search in c['customer_name'] or search in c['pid']]

    return jsonify({
        'customers': filtered[start:end],
        'total': len(filtered),
        'pages': (len(filtered) + per_page - 1) // per_page
    })

@admin_bp.route('/customers', methods=['POST'])
@jwt_required()
def add_customer():
    data = request.get_json()
    # 模拟添加客户
    new_id = str(int(customers_db[-1]['customer_id']) + 1)
    new_customer = {
        'customer_id': new_id,
        'customer_name': data['customerName'],
        'pid': data['pid'],
        'telephone': data['telephone'],
        'address': data.get('address', '')
    }
    customers_db.append(new_customer)
    return jsonify({'success': True, 'message': '客户添加成功'}), 201

@admin_bp.route('/customers/<customer_id>', methods=['PUT'])
@jwt_required()
def update_customer(customer_id):
    data = request.get_json()
    for customer in customers_db:
        if customer['customer_id'] == customer_id:
            customer['customer_name'] = data['customerName']
            customer['pid'] = data['pid']
            customer['telephone'] = data['telephone']
            customer['address'] = data.get('address', '')
            return jsonify({'success': True, 'message': '客户更新成功'})
    return jsonify({'success': False, 'message': '客户不存在'}), 404

@admin_bp.route('/customers/<customer_id>', methods=['DELETE'])
@jwt_required()
def delete_customer(customer_id):
    global customers_db
    customers_db = [c for c in customers_db if c['customer_id'] != customer_id]
    return jsonify({'success': True, 'message': '客户删除成功'})

# 银行卡管理路由 - 新增
@admin_bp.route('/cards', methods=['GET'])
@jwt_required()
def get_cards():
    customer_id = request.args.get('customer_id')
    if customer_id:
        filtered = [c for c in cards_db if c['customer_id'] == customer_id]
    else:
        filtered = cards_db
    return jsonify({'cards': filtered})

@admin_bp.route('/cards', methods=['POST'])
@jwt_required()
def add_card():
    data = request.get_json()
    # 模拟添加银行卡
    new_card = {
        'card_id': f'622202{len(cards_db) + 10000000000}',
        'customer_id': data['customer_id'],
        'deposit_type': data['deposit_type'],
        'balance': float(data.get('initial_balance', 0)),
        'open_date': data['open_date'],
        'is_report_loss': False
    }
    cards_db.append(new_card)
    return jsonify({'success': True, 'message': '银行卡添加成功', 'card': new_card}), 201

# 存款业务管理路由 - 新增
@admin_bp.route('/deposits', methods=['GET'])
@jwt_required()
def get_deposits():
    card_id = request.args.get('card_id')
    if card_id:
        filtered = [d for d in deposits_db if d['card_id'] == card_id]
    else:
        filtered = deposits_db
    return jsonify({'deposits': filtered})

# 交易管理路由 - 新增
@admin_bp.route('/transactions', methods=['GET'])
@jwt_required()
def get_transactions():
    card_id = request.args.get('card_id')
    if card_id:
        filtered = [t for t in transactions_db if t['from_card'] == card_id or t['to_card'] == card_id]
    else:
        filtered = transactions_db
    return jsonify({'transactions': filtered})

# 统计报表路由 - 新增
@admin_bp.route('/reports/overview', methods=['GET'])
@jwt_required()
def get_overview_report():
    total_customers = len(customers_db)
    total_cards = len(cards_db)
    total_deposits = sum(d['amount'] for d in deposits_db)
    total_transactions = len(transactions_db)
    
    return jsonify({
        'total_customers': total_customers,
        'total_cards': total_cards,
        'total_deposits': total_deposits,
        'total_transactions': total_transactions
    })